
<template>
    
    <div class="main-page">
        
        <div class="block">
            <h3 class="money-title">交易金额</h3>
            <div class="money-box">
                <div class="money-icon"><img src="@/assets/managemoney/money-icon.png"></div>
                <div class="money-input">
                    <input type="text" 
                    readonly
                    clickable 
                    v-model="manageMoneyDetailInfo.money" 
                    placeholder="0.00"
                    @click="openKeyboardShow">
                </div>
            </div>
        </div>
        <div class="block">
            <div class="choose-box">
                <div class="way-box">
                    <span  :class="[isPayOut ? 'way active':'way']" @click="selectWay('支出')">支出</span>&nbsp;
                    <span  :class="[isPutIn  ? 'way active':'way']" @click="selectWay('收入')">收入</span>
                </div>
                
            </div>
            <div class="types-box">
                <template v-if="isPayOut == true" >
                    <template v-for="(item,index,key) in payOutTypeList"> 
                        
                    <div class="type" :key="key" @click="selectType(item.name)" v-if="index <= 8">
                        <img :src="[manageMoneyDetailInfo.typeName == item.name ? item.iconselected : item.icon]"><br>
                        <span class="type-name">{{item.name}}</span>
                    </div>
                    </template>
                    <div class="type"  @click="selectType(item.name)" v-if="payOutTypeList.length > 8" >
                        <img src="../../assets/managemoney/types/more-icon.png" ><br>
                        <span class="type-name">更多</span>
                    </div>
                </template> 
                <template v-if="isPutIn == true" >
                    <template  v-for="(item,index,key) in putInTypeList"> 
                    <div class="type" :key="key" @click="selectType(item.name)" v-if="index <= 8 ">
                        <img :src="[manageMoneyDetailInfo.typeName == item.name ? item.iconselected : item.icon]"><br>
                        <span class="type-name">{{item.name}}</span>
                    </div>
                    </template>
                        
                    <div class="type"  @click="selectType(item.name)" v-if="putInTypeList.length > 8" >
                        <img src="../../assets/managemoney/types/more-icon.png" ><br>
                        <span class="type-name">更多</span>
                    </div>
                </template>

            </div>
        </div>
         <div class="block">
            <h3 class="money-title">备注</h3>
            <div class="remark-box">
                <textarea class="content" v-model="manageMoneyDetailInfo.remark">
                 
                </textarea>
             
                <!-- <span class="remark-btn" @click="showIsRemarkShow" v-if="manageMoneyDetailInfo.remark == ''">{{remarkBtnTxt}}</span>
                <span class="remark-btn" @click="showIsRemarkShow" v-if="manageMoneyDetailInfo.remark != ''">修改</span> -->
            </div>
         </div>


    
        <div class="choose-date-block" @click="showDateSelectBox">
            <span class="date">{{manageMoneyDetailInfo.createTime}}</span>
        </div>


        <div class="submit-block">
            <div class="block">
                <button class="sub-btn" @click="submitForm">确定添加</button>
            </div>
        </div>

        <van-number-keyboard
            
            theme="custom"
            extra-key="."
            close-button-text="确定"
            @input="onInput"
            @delete="onDelete"
            @close = "submitForm"
            @blur="keyboardShow = false"
            :show="keyboardShow"
            :maxlength="20"
            
        />

        <!-- 日期选择 -->
        <van-popup
            v-model="dateSelectBoxShow"
            round 
            @open="hidePopup"
            position="bottom"
            :style="{ height: '264px' }"
        >

            <van-datetime-picker
                @confirm="sureSelectDate"
                @cancel="cancelSelectDate"
                :formatter="dateFormatter"
                v-model="currentDate"
                type="date"
                title="选择日期"
                :max-date="maxDate"
            />
        </van-popup>


    </div>
</template>
<script>
    import axios from 'axios';
    // import 'muse-ui-loading/dist/muse-ui-loading.css'; // load css
    // import Loading from 'muse-ui-loading';
    
    import wx from 'weixin-js-sdk';

    import 'vant/lib/index.css';
    import { Popup } from 'vant';
    import { Icon } from 'vant';
    import { DatetimePicker } from 'vant';
    import { NumberKeyboard } from 'vant';
    import { Field,Toast } from 'vant';
    import { Empty } from 'vant';

    import workicon from '../../assets/managemoney/types/work-icon.png'
    import buyicon from '../../assets/managemoney/types/buy-icon.png'
    import trafficicon from '../../assets/managemoney/types/traffic-icon.png'
    import defaulticon from '../../assets/managemoney/types/default-icon.png'

    import workiconselected from '../../assets/managemoney/types/work-icon-selected.png'
    import buyiconselected from '../../assets/managemoney/types/buy-icon-selected.png'
    import trafficiconselected from '../../assets/managemoney/types/traffic-icon-selected.png'
    import defaulticonselected from '../../assets/managemoney/types/default-icon-selected.png'

	import { mapState, mapActions } from 'vuex'
    export default {
        name: 'Login',
        
        components: {
            [Popup.name]: Popup,
            [Icon.name]: Icon,
            [DatetimePicker.name]: DatetimePicker,
            [NumberKeyboard.name]: NumberKeyboard,
            [Field.name]: Field,
            [Toast.name]: Toast,
            [Empty.name]: Empty,
        },
        data(){
            return{
                isManageMoneyBookNameShow:false,
                clickTypeName:'',
                show:false,
                isPayOut:false,
                dateSelectBoxShow:false,
                isPutIn:false,
                isRemarkShow:false,
                remarkBtnTxt:'添加备注',
                keyboardShow:false,
                currentDate: new Date(),
                maxDate: new Date(),
                manageMoneyDetailInfo:{
                    createTime: "",
                    manageMoneyBookId: "",
                    manageMoneyBookName:"",
                    money: "",
                    remark: '',
                    typeName: "",
                    way: "",
                    createUserId:''
                },
                tempManageMoneyDetailInfo:{},
                manageMoneyBookInfo:{
                    id:'',
                    title:'',
                    createTime:'',
                    nowMonthPayOut:'',
                    nowMonthPutIn:'',
                },
                dataList:[],
                payOutTypeList:[
                    {name:'办公用品',icon:workicon,iconselected:workiconselected},
                    {name:'采购',icon:buyicon,iconselected:buyiconselected},
                    {name:'交通',icon:trafficicon,iconselected:trafficiconselected},
                    {name:'油费',icon:defaulticon,iconselected:defaulticonselected},
                    {name:'房租',icon:defaulticon,iconselected:defaulticonselected},
                    {name:'购物',icon:defaulticon,iconselected:defaulticonselected},
                    {name:'手机话费',icon:defaulticon,iconselected:defaulticonselected},
                    {name:'水费',icon:defaulticon,iconselected:defaulticonselected},
                    {name:'电费',icon:defaulticon,iconselected:defaulticonselected},
                    {name:'气费',icon:defaulticon,iconselected:defaulticonselected},
                    {name:'娱乐',icon:defaulticon,iconselected:defaulticonselected},
                    {name:'旅游',icon:defaulticon,iconselected:defaulticonselected}
                ],
                putInTypeList:[
                    {name:'工资',icon:defaulticon,iconselected:defaulticonselected},
                    {name:'预支款',icon:defaulticon,iconselected:defaulticonselected},
                    {name:'奖金',icon:defaulticon,iconselected:defaulticonselected},
                    {name:'转账',icon:defaulticon,iconselected:defaulticonselected},
                    {name:'其他',icon:defaulticon,iconselected:defaulticonselected}
                ]
            }
        },
		computed: mapState({
			application: state => state.application.systemInfo,
			userId: state => state.login.userId,
			loginInfo: state => state.login.loginInfo,
			isLogin: state => state.login.isLogin,
			wxInfo:state => state.login.wxInfo,
			redirectFullPath:state => state.login.redirectFullPath
		}),
        created: function () {
            this.getManageMoneyBookDetail();
            this.getManageMoneyDetailDataList();
            this.initDate(new Date());
            this.isPayOut = true;
            this.manageMoneyDetailInfo.way = '支出';
            // this.tempManageMoneyDetailInfo = JSON.parse(JSON.stringify(this.manageMoneyDetailInfo));
            // this.jsSDKConfig();
        },
        methods: {
            returnDate(dateObj){
                var value = this.manageMoneyBookInfo.createTime;
                var date = '';
                if(value.date != undefined){
                     date = value.date.year + "年" + value.date.month + "月" + value.date.day + "日";
                }              
                return date;
            },
            infoPage(id){
                this.$router.push({query:{id:id},path:'/expense/book/info'})
            },
            cancelNameSubmit(){
                this.hideInputName();
            },
            sureNameSubmit(){
                this. updateManageMoneyBookInfo();
                this.hideInputName();
            },
            hideInputName(){
                this.isManageMoneyBookNameShow = false;
            },
            openInputName(){
                this.isManageMoneyBookNameShow = true;
            },
            submitForm(){
                var that = this;
                var userId = this.userId;
                this.manageMoneyDetailInfo.createUserId = userId;
                
                if(this.manageMoneyDetailInfo.money == ""){
                   Toast.fail("请输入金额");
                   this.openKeyboardShow();
                   return false;
                }
                
                if(this.manageMoneyDetailInfo.typeName == ""){
                    Toast.fail("请选择记账类型");
                    return false;
                }
                this.manageMoneyDetailInfo.money = parseFloat(this.manageMoneyDetailInfo.money).toFixed(2);
                this.manageMoneyDetailInfo.expenseBookName =  this.manageMoneyBookInfo.title;
                this.manageMoneyDetailInfo.expenseBookId =  this.manageMoneyBookInfo.id;
                axios.post("/api/expenseBookDetail/save",this.manageMoneyDetailInfo)
                .then(res=>{
                    console.log('res=>',res);     
                    if(res.data == "success"){

                        // that.manageMoneyDetailInfo = JSON.parse(JSON.stringify(that.tempManageMoneyDetailInfo));    
                        // that.getManageMoneyBookDetail();
                        // that.getManageMoneyDetailDataList();
                        // // that.updateManageMoneyBookInfo();
                        // that.initDate(new Date());
                        // that.isPayOut = true;
                        // that.isPutIn = false;
                        // that.manageMoneyDetailInfo.way = '支出';
                       
                        Toast.success("记账成功");
                    } else{
                        Toast.fail(res.data.msg);
                    }
                })
            },
            updateManageMoneyBookInfo(){
                this.manageMoneyBookInfo.nowMonthPayOut = this.monthSumMoney('支出');
                this.manageMoneyBookInfo.nowMonthPutIn = this.monthSumMoney('收入');
                this.manageMoneyBookInfo.createTime = '';
                axios.post("/api/expenseBookInfo/update",JSON.stringify(this.manageMoneyBookInfo))
                .then(res=>{
                    // console.log('res=>',res);     
                    if(res.data == "success"){
                        Toast.success("账本数据已更新");
                    } else{
                        Toast.fail(res.data.msg);
                    }
                })
            },
            detailListIcon(typeName){
                for(var i =0; i < this.payOutTypeList.length; i ++){
                    if(this.payOutTypeList[i].name == typeName){
                        return this.payOutTypeList[i].icon;
                    }
                }
                for(var i =0; i < this.putInTypeList.length; i ++){
                    if(this.putInTypeList[i].name == typeName){
                        return this.putInTypeList[i].icon;
                    }
                }
            },
            selectType(typeName){
                this.manageMoneyDetailInfo.typeName = typeName;
            },
            openKeyboardShow(){
                this.keyboardShow = true;
            },

            selectWay(way){
                if(way == '支出'){
                     this.isPayOut = true;
                     this.isPutIn = false;
                     this.manageMoneyDetailInfo.way = '支出';
                } else if(way == '收入'){
                    this.isPayOut = false;
                    this.isPutIn = true;
                    this.manageMoneyDetailInfo.way = '收入';
                }
            },
            showIsRemarkShow(){
                this.isRemarkShow = true;
            },
            hideIsRemarkShow(){
                this.isRemarkShow = false;
                this.showPopup();
            },
            onInput(value) {
                this.manageMoneyDetailInfo.money += value;
                // 限制只能输入一个小数点及两位小数
                this.manageMoneyDetailInfo.money = this.manageMoneyDetailInfo.money.toString().match(/^\d*(\.?\d{0,2})/g)[0] || this.manageMoneyDetailInfo.money;

            },
            onDelete() {
                let flag = true
                if (flag) {
                    // 删除掉字符串最后一个
                    this.manageMoneyDetailInfo.money = this.manageMoneyDetailInfo.money.substring(0, this.manageMoneyDetailInfo.money.length - 1)
                    if (this.manageMoneyDetailInfo.money.length === 0) {
                        flag = false
                        return false
                    }
                }
            },
            sureSelectDate(val){
                this.initDate(val);
                //console.log(date);
                this.showPopup();
                this.hideDateSelectBox();

            },
            cancelSelectDate(){
                this.showPopup();
                this.hideDateSelectBox();
            },
            initDate(val){
                let year = val.getFullYear()//年
                let month = val.getMonth() + 1//月
                let day = val.getDate()//日
                let hour = val.getHours()//时
                let minute = val.getMinutes()//分
                if (month >= 1 && month <= 9) { month = `0${month}` }
                if (day >= 1 && day <= 9) { day = `0${day}` }
                if (hour >= 0 && hour <= 9) { hour = `0${hour}` }
                if (minute >= 0 && minute <= 9) { minute = `0${minute}` }
                // this.user_birthday = `${year}-${month}-${day} ${hour}:${minute}`
                var date = `${year}年${month}月${day}日`
                this.manageMoneyDetailInfo.createTime = date;
            },
            dateFormatter(type, val) {
                if (type === 'year') {
                    return `${val}年`;
                } else if (type === 'month') {
                    return `${val}月`;
                } else if(type === 'day'){
                    return `${val}日`;
                }
                return val;
            },
            daySumMoney(array,wayStr){
                var float = 0.00;
                for(var index = 0 ; index < array.length; index ++){
                    var money = array[index].money;
                    var way =  array[index].way;
                    if(way == wayStr){
                        float += parseFloat(money);
                    }
                    
                }
                return float.toFixed(2);
            },
            monthSumMoney(wayStr){
                var float = 0.00;
                for(var i = 0; i < this.dataList.length; i ++){
                    var array = this.dataList[i].arrays;
                    for(var index = 0 ; index < array.length; index ++){
                        var money = array[index].money;
                        var way =  array[index].way;
                        if(way == wayStr){
                            float += parseFloat(money);
                        }
                        
                    }
                }
                return float.toFixed(2);
            },
            showDateSelectBox(){
                this.dateSelectBoxShow = true;
            },
            hideDateSelectBox(){
                this.dateSelectBoxShow = false;
            },
            hidePopup(){
                this.show = false;
            },
            showPopup() {
                // this.manageMoneyDetailInfo = JSON.parse(JSON.stringify(this.tempManageMoneyDetailInfo));  
                this.show = true;
            },

            getManageMoneyBookDetail(){
                var that = this;
                var manageMoneyBookId = this.$route.query.manageMoneyBookId;
                    // 上面的请求也可以这样做
                axios.get('/api/expenseBookInfo/info?id=' + manageMoneyBookId)
                .then(function (response) {
                    that.manageMoneyBookInfo = response.data.data;
                    
                })
                .catch(function (error) {
                    console.log(error);
                });
            },
            getManageMoneyDetailDataList(){
                var that = this;
                var manageMoneyBookId = this.$route.query.manageMoneyBookId;
                    // 上面的请求也可以这样做
                axios.get('/api/expenseBookDetail/list/bygroupdate?expenseBookId=' + manageMoneyBookId)
                .then(function (response) {
                    that.dataList = JSON.parse(response.data.data);
                   
                    if(that.manageMoneyBookInfo.nowMonthPayOut != that.monthSumMoney('支出') || that.manageMoneyBookInfo.nowMonthPutIn != that.monthSumMoney('收入')){
                        that.updateManageMoneyBookInfo();
                    }
                })
                .catch(function (error) {
                    console.log(error);
                });
            },
            jsSDKConfig(){
                var url = encodeURIComponent(window.location.href.split('#')[0]);
                this.axios.get('/api/weixin/getJsConfig?url='+url)
                .then(function (response) {
					var jsConfig = response.data.data;
					jsConfig = JSON.parse(jsConfig);
                    wx.config({
                        debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
                        appId: jsConfig.appId, // 必填，公众号的唯一标识
                        timestamp: jsConfig.timestamp, // 必填，生成签名的时间戳
                        nonceStr: jsConfig.nonceStr, // 必填，生成签名的随机串
                        signature: jsConfig.signature,// 必填，签名
                        jsApiList: ['hideAllNonBaseMenuItem','onMenuShareAppMessage','updateAppMessageShareData','showMenuItems'] // 必填，需要使用的JS接口列表
                    });
                    wx.ready(function () {   //需在用户可能点击分享按钮前就先调用
                        wx.hideAllNonBaseMenuItem();
                        // wx.showMenuItems({
                        //     menuList: ['menuItem:share:appMessage','menuItem:share:timeline'] // 要显示的菜单项，所有menu项见附录3
                        // });
                        // wx.onMenuShareAppMessage({ 
                        //     title: '一路向北', // 分享标题
                        //     desc: '小功能', // 分享描述
                        //     link: encodeURIComponent(window.location.href.split('?')[0]), // 分享链接，该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
                        //     imgUrl: '', // 分享图标
                        //     type: '', // 分享类型,music、video或link，不填默认为link
                        //     dataUrl: '', // 如果type是music或video，则要提供数据链接，默认为空
                        //     success: function () {
                        //     // 设置成功
                        //     }
                        // })
                    });
                    
                })
                .catch(function (error) {
                    console.log(error);
                });
            },
            tips(){
                this.$alert(this.tipMsg, '提示', {
                    okLabel: '知道了'
                }).then(() => {
                    
                });
            },
           
        }
    }

</script>

<style scoped>

    .main-page{
        background-color: #f8f8f8;
        height: 100%;
    }
    .block{
        background-color: #ffffff;
        margin-bottom: 8px;
    }
    .head-box{
        height: auto;
        overflow: hidden;
        padding: 16px;
        background-color: #3387FB;   
        color: white;
         font-family: '微软雅黑';
         text-align: left;
    }

    .head-box p{
        font-size: 16px;
    }

    .pay-list-box{
        padding: 16px;
        border-bottom: 1px solid #eee;
            background-color: #ffffff;
    }

    .pay-info-box{
        height: 50px;
        width: 100%;
        position: relative;
    }
    

   .icon-box{
        position:absolute;
        width: 50px;
        height: 50px;
        left: 0px;
    }
    
    .icon-box img{
        width:100%;
        height: 100%;
    }

    .content-box{
        position:absolute;
        right: 0px;
        height: 100%;
        left: 65px;
        font-size: 16px;
        font-weight: bold;
        text-align: left;
         font-family: '微软雅黑';
    }
    .content-box .title{
        height: 30px;
        line-height: 30px;
         font-family: '微软雅黑';
    }
     .content-box .title .left{
        float: left;
    }
    .content-box .title .money{
        float: right;  
         font-family: '微软雅黑';
    }
    .content-box .desc{
        color: #dddddd;
        font-weight: normal;
         font-family: '微软雅黑';
    }

    .add-btn{
        position:fixed;
        bottom: 10%;
        right: 32px;
        width: 50px;
        height: 50px;
        background-image: url('../../assets/managemoney/add-btn-icon.png');
        background-repeat: no-repeat;
        background-size: 100%;
        border-radius: 50%;
        box-shadow: 1px 1px 10px #3387FB;
        background-color: white;
    }

    .pay-panel-box{
        background-color: #eeeeee;
        padding: 8px;
        min-height: 500px;
    }

    .panel-box{
        border-radius: 10px;
        height: auto;
        overflow: hidden;
        background-color: white;
        margin-bottom: 8px;
    }
   

    .money-title{
        text-align: left;
        margin: 0px;
        padding: 16px;
    }

    .month-box{
        font-size: 16px;
        font-weight: bold;
        text-align: left;
        padding: 24px 16px;
        background-color: #fafafa !important;
        position: relative;
      
    }

    .month-box .right{
        position:absolute;
        left:0px;
        right: 0px;
        bottom: 0px;
        top:0px;
        right: 0px;
        padding: 26px 16px;
        text-align: right;
        font-weight: normal;
        font-size: 12px;
    }

    .month-box .right .payout{
        padding-right: 8px;
    }
     .month-box .right .putin{
        padding-left: 8px;
    }

    .choose-box{
        padding: 16px;
        padding-top:16px;
        font-size: 16px;
        border-bottom: 1px solid #eeeeee;
    }
    .way-box{
        /* width: 40%; */
        /* float: left; */
        text-align:left;
    }
    .way-box > span{
        border-radius: 20px;
    }

    .way-box .active{
        background-color: #cee3ff;
        border: 1px solid #cee3ff;
        color: #3387FB;
    }

    .way{
        padding: 8px 16px;
        /* border:1px solid #ebedf0; */
        
    }
    .date-box{
        width: 50%;
        float: left;
        text-align: left;
        padding-left: 16px;
    }

    .date{
        padding:  4px 8px;
        /* border:1px solid #ebedf0; */
        padding: 12px 24px;
        border-radius: 40px;
        color: #3387FB;
    }

    .money-box{
        height: 50px;
        padding-left: 16px;
        border-bottom: 1px solid #eeeeee;
        position: relative;
    }
    .money-box .money-icon{
        width: 30px;
        height: 100%;
        line-height: 70px;
        float: left;
    }
    .money-box .money-icon img{
        width: 100%;
    }

    .money-box .money-input{
        position: absolute;
        left: 46px;
        right: 16px;
        top:0px;
        bottom:0px;
    }
    .money-box .money-input input{
        width: 100%;
        height: 100%;
        font-size: 32px;
        font-weight: bold;
        /* color: #3387FB; */
        border: none;
        outline: none;
        background-color: unset;
    }
    .remark-box{
        height: auto;
        min-height: 50px;
        overflow: hidden;
        padding: 0px 16px;
        padding-bottom: 16px;
        text-align: left;
    }
    .remark-box .remark-btn{
        color: #3387FB;
        font-size: 16px;
    }

    .remark-box .content{
        font-size: 16px;
        color: #969799;
        width: 100%;
        border: 1px solid #eeeeee;
        min-height: 100px;
        outline: none;
    }

    .remarkTextArea{
        padding-top: 32px !important;
    }
    .van-cell::after{
        border-bottom: 0px;
    }

    .types-box{
        padding: 16px 0px;
        padding-top: 0px;
        height: auto;
        text-align: left;
        /* overflow-y: hidden;
        overflow-x: auto; */
        /* white-space: nowrap; */
    }
    .types-box .type{
        width: 20%;
        text-align: center; 
        margin-top: 16px;
        position: relative;
        display: inline-block;
    }
    .types-box .type img{
        height: 40px;
    }

    .types-box .type  .type-name{
        font-size: 12px;
    }
    .van-number-keyboard .van-key{
        height: 40px !important;
        border-radius: 0px !important;
    }


    .popup-title-box{
        height: 56px;
            display: -webkit-box;
        display: -webkit-flex;
        display: flex;
        -webkit-box-align: center;
        -webkit-align-items: center;
        align-items: center;
        -webkit-box-pack: justify;
        -webkit-justify-content: space-between;
        justify-content: space-between;
    }

    .popup-title-box .title-txt{
        max-width: 50%;
        font-weight: 500;
        font-size: 16px;
        line-height: 20px;
        text-align: center;
    }

    .popup-title-box button{
        height: 100%;
        padding: 0 16px;
        font-size: 14px;
        background-color: transparent;
        border: none;
        cursor: pointer;
        
    }

    .popup-title-box .cancel-btn{
        color: #969799;
    }

    .popup-title-box .sure-btn{
        color: #576b95;
    }
    .van-empty{
        height: 500px;
        background-color: white;
    }

    .choose-date-block{
        /* background-color: #ffffff;
        border: 1px solid #eeeeee; */
        padding: 16px ;
        float: left;
    }
    .choose-date-block .date{
        background-color: #ffffff;
    }
    .submit-block{
        position: fixed;
        bottom: 0px;
        left: 0px;
        right: 0px;
    }
    .submit-block > .block{
        margin-bottom: 0px;
    }
    .sub-btn{
        padding: 8px 40px;
        border: none;
        background-color: #3387FB;
        color: white;
        letter-spacing: 4px;
        height: 40px;
        /* line-height: 40px; */
        border-radius: 40px;
        margin:10px;
    }
</style>